import React, { useEffect, useState } from "react";
import { Text, View, Animated, StyleSheet, TouchableHighlight, TouchableOpacity, Linking, ScrollView, Alert, TextInput, Platform, Image ,Keyboard} from "react-native";
import * as S from "../Home/styles";
import { Avatar, HStack, Center, NativeBaseProvider, ChevronRightIcon, useToast, ArrowBackIcon, AddIcon, DeleteIcon ,Modal} from "native-base";
import { launchImageLibrary, launchCamera } from 'react-native-image-picker';
import { RFValue } from "react-native-responsive-fontsize";
import { useGlobal } from '../../utils/GlobalContext';
import { bucketList,bucketAdd,bucketDel,bucketUpdate} from "../../services/user";
import { CommonActions } from '@react-navigation/native';
import { ImageMap } from "../../constants/categories";
import { SwipeListView } from 'react-native-swipe-list-view';
import EmptyView from "../../components/EmptyView";
import Toast from "react-native-toast-notifications";
import {Icon} from '../../components/Icon/index'


const rowSwipeAnimatedValues = {};
const SwipeValueBasedUi = ({listData,setModalVisibleEditFun,setModalVisibleDelFun}:any) => {
  

  const closeRow = (rowMap, rowKey) => {
    if (rowMap[rowKey]) {
      rowMap[rowKey].closeRow();
    }
  };

  const deleteRow = (rowMap, rowKey) => {
    // closeRow(rowMap, rowKey);
    // const newData = [...listData];
    // const prevIndex = listData.findIndex(item => item.key === rowKey);
    // newData.splice(prevIndex, 1);
    // setListData(newData);
  };

  const onRowDidOpen = rowKey => {
    // console.log('This row opened', rowKey);
  };

  const onSwipeValueChange = swipeData => {
    const { key, value } = swipeData;
    rowSwipeAnimatedValues[key].setValue(Math.abs(value));
  };

  const renderItem = data => (
    <View style={styles2.rowFront}>
      <Text style={styles2.rowFrontTextTitle}>{data.item.name}</Text>
      <Text style={styles2.rowFrontTextTime}>{data.item.createTime}</Text>
    </View>
  );

  const renderHiddenItem = (data, rowMap) => (
    <View style={styles2.rowBack}>
      <TouchableOpacity
        style={[styles2.backRightBtn, styles2.backRightBtnRight]}
        onPress={() => {
          closeRow(rowMap, data.item.key);
          setModalVisibleDelFun(data.item.id)
        }}
      >
        <Animated.View
          style={[
            styles2.trash,
            data.item.key
            &&
            data.item.name  
            &&
            {
                transform: [
                    {
                        scale:  rowSwipeAnimatedValues[ data.item.key ].interpolate({
                            inputRange: [45, 90],
                            outputRange: [0, 1],
                            extrapolate: 'clamp',
                        }),
                    },
                ],
            },
        ]}
        >
          <DeleteIcon color={'#fff'}  style={styles2.trash} />
        </Animated.View>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles2.backRightBtn, styles2.backRightBtnRight2]}
        onPress={() => {
          closeRow(rowMap, data.item.key);
          setModalVisibleEditFun(data)

        }}
      >
        <Animated.View
          style={[
            styles2.trash,
            data.item.key
            &&
            data.item.name  
            &&
            {
                transform: [
                    {
                        scale:  rowSwipeAnimatedValues[ data.item.key ].interpolate({
                            inputRange: [90, 135],
                            outputRange: [0, 1],
                            extrapolate: 'clamp',
                        }),
                    },
                ],
            },
        ]}
        >
          <Icon style={{fontSize:25}} color={ '#fff'} name="create"/>
        </Animated.View>
      </TouchableOpacity>
    </View>
  );

  const renderEmptyComponent = () => {
    return <EmptyView/>;
  }

  return (
    <View style={styles2.container}>
      <SwipeListView
        showsVerticalScrollIndicator={false}
        data={listData}
        renderItem={renderItem}
        renderHiddenItem={renderHiddenItem}
        // leftOpenValue={75}
        rightOpenValue={-150}
        previewRowKey={'0'}
        disableRightSwipe={true}
        previewOpenValue={0}
        previewOpenDelay={3000}
        onRowDidOpen={onRowDidOpen}
        onSwipeValueChange={onSwipeValueChange}
        ListEmptyComponent={renderEmptyComponent}
      />
    </View>
  );
}



const Title = ({ navigation, addBtn,setSubName,setSubId }: any) => {
  return (
    <View style={styles.titleBox}>
      <TouchableOpacity
        style={styles.backBtn}
        onPress={() => {
          navigation.goBack()
        }}
      >
        <ArrowBackIcon size="5" />
      </TouchableOpacity>
      <Text style={styles.titlText}>遗愿清单</Text>
      <TouchableOpacity
        style={[styles.backBtnRight]}
        onPress={() => {
          // navigation.goBack()
          setSubName('')
          setSubId('')
          addBtn(true)
        }}
      >
        <AddIcon size="5" />
      </TouchableOpacity>
    </View>
  )
}

const AddModal = ({modalVisible,setModalVisible,loadPageList,subName,subId}:any)=>{
  


  const toast = useToast();
  const modalToastRef = React.useRef();


  const [name,setName] = useState('')

  useEffect(() => {
    setName(subName)    
  }, [subName]);


  const bucketAddFun = (modalToastRef)=>{
    // loadPageList()
    // setName('')
    // setModalVisible(false)


    // return

    let obj = {
      name,
      id:subId
    }

    

    if(!name){
      modalToastRef.current.show("请输入遗愿", {
        type: "defult",
        placement: "top"
      });
      return
    }

    console.log(obj)

    if(subName){
      bucketUpdate(obj).then(res=>{
        setModalVisible(false)
        Keyboard.dismiss();
        loadPageList()
        setName('')
      })
    }else{
      bucketAdd(obj).then(res=>{
        setModalVisible(false)
        Keyboard.dismiss();
        loadPageList()
        setName('')
        
        
      })
    }


    

  }
  
  const onChangeName = (text)=>{
    setName(text)
  }

  return (
    <Modal
        isOpen={modalVisible}
        onClose={()=>{setModalVisible(false)}}
        
      >
        <Toast offsetTop={50} ref={modalToastRef} />
        <View style={styles3.centeredView2}>
          <View style={styles3.modalView}>
            <View style={styles3.topBox}>
              <Text style={styles3.topBoxTitle}>{subName ? '编辑': '新增'}遗愿清单</Text>
              <View style={styles3.inputBox}>
                                
                <TextInput
                  style={styles3.input}
                  placeholder='请输入'
                  placeholderTextColor='#D1D1D6'
                  onChangeText={text => onChangeName(text)}
                  defaultValue={subName}
                />
              </View>
            </View>

            
            <View style={styles3.bottomBtns}>
              <TouchableOpacity
                style={[styles3.bottomBtnItem, styles3.bottomBtnItem2]}
                onPress={() => {
                  setName('')
                  Keyboard.dismiss();
                  setModalVisible(false)
                  
                }}
              >
                <Text style={[styles3.textStyle, { color: 'rgba(0,0,0,.64)' }]}>取消</Text>

              </TouchableOpacity>
              <TouchableOpacity
                style={styles3.bottomBtnItem}
                onPress={() => {
                  bucketAddFun(modalToastRef)
                }}
              >
                <Text style={styles3.textStyle}>确认</Text>

              </TouchableOpacity>
            </View>



          </View>
        </View>
      </Modal>
  )
}

const DelModal = ({modalVisible,setModalVisible,bucketDelFun}:any)=>{
  return (
    <Modal
        isOpen={modalVisible}
        onClose={()=>{setModalVisible(false)}}
        
      >
        <View style={[styles3.centeredView2]}>
          <View style={styles3.modalView}>
            <View style={styles3.topBox}>
              <Text style={[styles3.topBoxTitle,{paddingTop:31,paddingBottom:37}]}>是否确认删除该清单？</Text>
            </View>

            
            <View style={styles3.bottomBtns}>
              <TouchableOpacity
                style={[styles3.bottomBtnItem, styles3.bottomBtnItem2]}
                onPress={() => {
                  setModalVisible(false)
                  
                }}
              >
                <Text style={[styles3.textStyle, { color: 'rgba(0,0,0,.64)' }]}>取消</Text>

              </TouchableOpacity>
              <TouchableOpacity
                style={styles3.bottomBtnItem}
                onPress={() => {
                  bucketDelFun()
                }}
              >
                <Text style={styles3.textStyle}>确认</Text>

              </TouchableOpacity>
            </View>



          </View>
        </View>
      </Modal>
  )
}


const LastWishList = ({ route, navigation }: any) => {

  const [modalVisible,setModalVisible] = useState(false)
  const [modalVisibleDel,setModalVisibleDel] = useState(false)

  const [listData, setListData] = useState([]);
  const [subName, setSubName] = useState('');
  const [subId, setSubId] = useState('');

  const [delId,setDelid] = useState('')

  const bucketDelFun = ()=>{
    let obj = {
      id:delId
    }
    bucketDel(obj).then(res=>{
      loadPageList()
      setModalVisibleDel(false)
      setDelid('')
    })
  }

  const setModalVisibleEditFun = (data)=>{
    console.log(data.item.name)
    setModalVisible(true)
    setSubName(data.item.name)
    setSubId(data.item.id)
  }

  const setModalVisibleDelFun = (id:any)=>{
    // Alert.alert(JSON.stringify(id))
    setDelid(id)
    setModalVisibleDel(true)
  }
  

  useEffect(() => {
    loadPageList()
    
  }, []);



  const loadPageList = ()=>{
    let obj = {
      pageNo:1,
      pageSize:9999
    }
    bucketList(obj).then(res=>{
      console.log(res.data.list)
      res.data.list
        .forEach((_, i) => {
            rowSwipeAnimatedValues[`${i}`] = new Animated.Value(0);
        });
      


      setListData(res.data.list
      .map((item, i) => ({ key: `${i}`, ...item })))
    })
  }

  



  return (
    <NativeBaseProvider>
      <S.GrayContainer style={{ backgroundColor: '#FFFFFF' }}>
        <View style={styles.container}>
          <Title navigation={navigation} setSubName={setSubName} setSubId={setSubId} route={route} addBtn={setModalVisible} />
          <SwipeValueBasedUi listData={listData} setModalVisibleEditFun={setModalVisibleEditFun} setModalVisibleDelFun={setModalVisibleDelFun} />
        </View>
      </S.GrayContainer>
      <AddModal loadPageList={loadPageList} subName={subName} subId={subId} modalVisible={modalVisible} setModalVisible={setModalVisible} />
      <DelModal bucketDelFun={bucketDelFun} modalVisible={modalVisibleDel} setModalVisible={setModalVisibleDel} />
    </NativeBaseProvider>
  );
};


export default LastWishList;





const styles2 = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    flex: 1,
  },
  backTextWhite: {
    color: '#FFF',
  },
  rowFront: {
    // alignItems: 'center',
    backgroundColor: 'rgba(226, 232, 242, 1)',
    paddingVertical:12,
    // height: 74,
    // minHeight:74,
    // flex:1,
    marginBottom:16,
    borderRadius:16,
    justifyContent:"center",
    paddingHorizontal:16,
    overflow:'hidden'
    
  },
  rowFrontTextTitle:{
    color:'#000000',
    fontSize:16,
    fontFamily:'HarmonyOS Sans SC',
    lineHeight:24,
  },
  rowFrontTextTime:{
    marginTop:4,
    color:'#8E8E93',
    fontFamily:'HarmonyOS Sans SC',
    fontSize:12,
  },
  rowBack: {
    alignItems: 'center',
    backgroundColor: 'rgba(226, 232, 242, 1)',
    flex: 1,
    marginBottom:16,
    // minHeight:74,
    // height:'',

    flexDirection: 'row',
    justifyContent: 'center',
    // paddingLeft: 15,
    borderRadius:16,
  },
  backRightBtn: {
    alignItems: 'center',
    bottom: 0,
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    width: 75,
    borderTopRightRadius:16,
    borderBottomRightRadius:16,
  },
  backRightBtnLeft: {
    backgroundColor: 'blue',
    right: 75,
  },
  backRightBtnRight: {
    backgroundColor: 'rgba(227, 73, 73, 1)',
    right: 0,
  },
  backRightBtnRight2: {
    backgroundColor: '#595959',
    right: 75,
    borderTopRightRadius:0,
    borderBottomRightRadius:0,
  },
  trash: {
    height: 25,
    width: 25,
  },
});



const styles = StyleSheet.create({
  container: {
    height: "100%",
    width: '100%',
    // alignItems:'center',
    paddingHorizontal: 24,

  },
  titleBox: {
    width: '100%',
    position: 'relative',
    alignItems: 'center',
    height: 40,
    justifyContent: "center",
    marginBottom: 26,
  },
  backBtn: {
    position: 'absolute',
    left: 0,
    backgroundColor: '#fff',
    width: 40,
    height: 40,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 100,

    shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    elevation: 3, // 阴影深度
  },
  backBtnRight: {

    position: 'absolute',
    right: 0,
    backgroundColor: '#fff',
    width: 40,
    height: 40,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 100,

    shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    elevation: 3, // 阴影深度
  },
  titlText: {
    fontSize: 17,
    fontWeight: '600',
    color: '#000000'
  },
  pageList: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  itemBox: {
    width: '25%',
    padding: 8,
  },
  pageItem: {
    // width:72,
    // height: 72,
    backgroundColor: '#F5F5F5',
    marginBottom: 16,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 16,
  },


})
const styles3 = StyleSheet.create({
  centeredView2: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: 'rgba(0,0,0,.6)',
    padding: 20,
  },
  modalView: {
    // margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    overflow: "hidden",
    alignItems: "center",
    shadowColor: "#000",
    justifyContent: 'center',
    width: '100%'
    // width:290)
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center"
  },
  bottomBtns: {
    flexDirection: 'row',
    width: "100%",
  },
  bottomBtnItem: {
    width: '50%',
    alignItems: 'center',
    justifyContent: 'center',
    // height: 48,
    // backgroundColor:'red',
    borderTopWidth: 1,
    borderColor: 'rgba(0,0,0,.1)',
    borderStyle: 'solid',
    paddingVertical:16,
  },
  bottomBtnItem2: {
    borderRightWidth: 1,
    borderColor: 'rgba(0,0,0,.1)',
    borderStyle: 'solid'
  },
  textStyle: {
    fontSize: 16,
    color: '#4371B1',
  },
  topBox: {
    padding: 14,
    paddingTop:22,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    // backgroundColor:'red'
  },
  topBoxTitle: {
    color: '#4371B1',
    fontSize: 18,
    fontWeight: '500',
    justifyContent: 'center',
    alignContent: 'center'
  },
  tags: {
    width: '100%',
    textAlign: 'left',
    backgroundColor: '#F5F5F5',
    marginTop: 12,
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 8,
    overflow: 'hidden',
    fontSize: 14,
    color: '#000000',
    marginBottom: 12,
  },
  inputBox: {
    flexDirection: 'row',
    width: '100%',
    alignItems:'center',
    marginTop:16,
    marginBottom:32,
  },
  inputItem: {
    width: "50%",

  },
  inputText: {
    fontSize: 12,
    color: '#000000',
    marginBottom: 4,

  },
  input: {
    // width: 110,
    flex:1,
    height: 40,
    borderColor: 'rgba(0,0,0,.2)',
    borderWidth: 1,
    borderRadius: 4,
    paddingHorizontal: 10,
    color:'#000'
  },
});
